import {router} from '@/router'
import type {R} from '@/api/type'
import {LoginInfo} from '@/type/user'
import Layout from '@/layout/index.vue'
import AuthorizeApi from '@/api/authorize'
import {generateRoute} from '@/util/route'
import UserStore from '@/store/module/user'
import StorageKey from '@/constant/storage-key'

export async function getDynamicRoute() {
    const userStore = UserStore()

    if (localStorage.getItem(StorageKey.USER_TOKEN)) {
        let result: R<LoginInfo> = await AuthorizeApi.authorize()
        userStore.setAuthorize(result?.data || {})

        router.addRoute({path: '/', component: Layout, children: generateRoute(UserStore().routeList)})

        generateRoute(userStore.routeList).forEach(a => router.addRoute('index', a))
    } else {
        localStorage.clear()
        sessionStorage.clear()
    }
}
